const express = require('express')
const next = require('next')
const createProxyMiddleware = require('http-proxy-middleware').createProxyMiddleware;
const hostname = '0.0.0.0'
const port = 9962
const dev = process.env.NODE_ENV !== 'production'
const app = next({
  dev,
  hostname,
  port,
  quiet: true,
  open: dev,
})
const handle = app.getRequestHandler()
async function start () {
  try {
    await app.prepare()
    const server = express()
    //写在这里可以获取环境变量
    const devProxy = {
      [process.env.NEXT_PUBLIC_BASE_API]: {
        target: 'http://stg.xinqiuzb.com:8200', // 外网测试环境
        changeOrigin: true,
        pathRewrite: { '^/api': '' },
      },
      // [process.env.NEXT_PUBLIC_WEBSOCKET_PUSH_API]: {
      //   target: 'ws://stg.xinqiuzb.com:8029', // 外网ws测试环境
      //   changeOrigin: true,
      //   ws: true,
      //   pathRewrite: { '^/wsapi': '' },
      // },
    }
    if (dev && devProxy) {
      Object.keys(devProxy).forEach((context) => {
        server.use(createProxyMiddleware(context, devProxy[context]))
      })
    }

    server.all('*', (req, res) => {
      handle(req, res)
    })

    server.listen(port, err => {
      if (err) {
        throw err
      }
      require('dns').lookup(require('os').hostname(), function (err, add, fam) {
        console.log(`> Ipv4 on http://${add}:${port}`)
      })
      // console.log(`http://0.0.0.0:${port}`)
      console.log(`> Ready on http://localhost:${port}`)
    })
  } catch (error) {
    console.log('An error occurred, unable to start the server')
    console.log(error)
  }
}
start()